package pers.vinsonws.jianghu.serverspring.channel;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @auther vinsonws
 * @date 2018/11/6 18:40
 */
@Service
public class ChannelManager {//这是目前的一种思路前提是service只会被实例化一次，如果不是这种方法不正确
    private static final Logger log = LoggerFactory.getLogger(ChannelManager.class);
    private Map<Integer, Channel> channelMap = new HashMap<>();//(userid,channel)
    private static ChannelManager instance;


    private ChannelManager() {}
    @PostConstruct
    private void createInstance(){
        this.instance = new ChannelManager();
        log.info("实例化ChannelManager");
    }


    public static ChannelManager getInstance(){
        return instance;
    }

    public boolean addChannel(Integer userId, Channel channel){
        if (userId == null || channel == null) throw new NullPointerException("用户id或者channel为空");
        channelMap.put(userId, channel);
        return true;
    }

    public boolean removeChannel(Integer userId){
        if (userId == null ) throw new NullPointerException("用户id为空");
        channelMap.remove(userId);
        return true;
    }

    public Channel getChannelByUserId(Integer userId){
        if (userId == null ) throw new NullPointerException("用户id为空");
        return channelMap.get(userId);
    }

    public int getCountOfChannel(){
        return channelMap.size();
    }

    public Set<Integer> getAllOnlineUserId(){
        return channelMap.keySet();
    }
}
